import store from '@/store';
import { cacheUtils } from '@/constants/util/cache-utils';

export const initByToken = (): Promise<boolean> => {
  return store
    .dispatch('users/initPfUsers')
    .then(res => {
      if (res) {
        const tenants = store.getters.tenants;
        return tenants?.length ? initByTenant(tenants[0].id) : false;
      } else {
        throw new Error('initPfUsers...' + res);
      }
    })
    .catch(err => {
      console.error('系统初始化：', err);
      return false;
    });
};
export const initByTenant = (tenId: string, appId?: string): Promise<boolean> => {
  const tenants = store.getters.tenants;
  let idx = -1;
  let tenant;
  if (tenants && (idx = tenants.findIndex((t: any) => t.id === tenId)) > -1) {
    tenant = tenants[idx];
  } else {
    return Promise.reject('tenants is empty or not found by ' + tenId);
  }
  return store
    .dispatch('users/initUsers', tenant.user)
    .then(res => {
      if (res) {
        return store.dispatch('apps/initApps', { tenId, appId });
      } else {
        throw new Error('initUsers...');
      }
    })
    .then(res => {
      if (res) {
        return store.dispatch('menus/initMenusByAppId');
      } else {
        throw new Error('initApps...' + res);
      }
    })
    .then(res => {
      if (res) {
        console.log('系统初始化完成...');
        return true;
      } else {
        throw new Error('initMenus...');
      }
    })
    .catch(err => {
      console.error('系统初始化：', err);
      return false;
    });
};
